<?php

namespace components\template;

class smarty {

    public $config;
    public $smarty;

    public function __construct($config) {
        $this->config = $config;
        $this->smarty = new \Smarty();
        $this->confSmarty($this->config);
    }

    public function confSmarty($config) {
        $default = TPL_PATH . $config['default'];
        $cache = TPL_PATH . '/system/cache';
        $compile = TPL_PATH . '/system/compile';
        $delimite = explode("|", $config['delimite']);
        $this->smarty->setTemplateDir($default);
        $this->smarty->setCacheDir($cache);
        $this->smarty->setCompileDir($compile);
        $this->smarty->setCaching($config['cache']);
        $this->smarty->setCacheLifetime($config['ctime']);
        $this->smarty->compile_check = true;
        $this->smarty->force_compile = $config['fcompile'];
        $this->smarty->debugging = $config['debug'];
        $this->smarty->left_delimiter = $delimite[0];
        $this->smarty->right_delimiter = $delimite[1];
        $this->getTplFun();
    }

    public function assign($tpl_var, $value = null, $nocache = false) {
        $this->smarty->assign($tpl_var, $value, $nocache);
    }

    public function display($template = null, $cache_id = null, $compile_id = null, $parent = null) {
        $this->smarty->display($template, $cache_id, $compile_id, $parent);
    }

    public function setTpldir($dir) {
        $this->smarty->setTemplateDir($dir);
    }
    public function setComDir($dir){
        $this->smarty->setCompileDir($dir);
    }

    public function tplFun($name, $fun) {
        $this->smarty->registerPlugin("function", $name, $fun);
    }

    public function tplBlock($name, $block) {
        $this->smarty->registerPlugin("block", $name, $block);
    }

    public function getTplFun() {
        require_once FRM_PATH . '/components/template/tags/core.tags.php';
        $this->tplFun("load", "load");
        $this->tplFun("import", "import");
        $this->getExTags('Fun');
        $this->getExTags('Block');
    }

    public function getExTags($type) {
        $dir = PRO_PATH . '/expand/tags/tag'.strtolower($type).'s';
        if (is_dir($dir)) {
            if ($handle = opendir($dir)) {
                while (false !== ($file = readdir($handle))) {
                    if ($file != "." && $file != "..") {
                        require_once $dir . '/' . $file;
                        if (substr($file, -4, 4) == '.php') {
                            $fun = explode(".php", $file);
                            $method = 'tpl'.$type;
                            $this->$method($fun[0], $fun[0]);
                        }
                    }
                }
            }
        }
    }

}

?>
